package com.ajie.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import com.ajie.config.annotation.RestControllerMapping;
import com.ajie.model.Result;
import com.ajie.utils.FileUtils;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Paths;
import java.util.UUID;

/**
 * @author: ajie
 * @createTime: 2024-07-14 19:25
 */
@SaIgnore
@RestControllerMapping("common")
public class CommonController {

    @PostMapping("upload")
    public Result<String> upload(@RequestBody MultipartFile file) {
        return Result.success("文件上传成功！", FileUtils.upload(file));
    }

    @SneakyThrows
    @GetMapping("view/{filename}")
    public void getImage(@PathVariable String filename, HttpServletResponse response) {
        String contextType = this.getContextType(filename);
        response.setContentType(contextType);
        // 使用ServletOutputStream写入图片数据
        try (ServletOutputStream out = response.getOutputStream();
             InputStream in = new BufferedInputStream(new FileInputStream(FileUtils.path + filename))) {
            if (contextType.equals("video/mp4")) {
                response.setContentLength(in.available());
            }
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }
    }

    private String getContextType(String filename) {
        String sufi = filename.substring(filename.lastIndexOf(".") + 1);
        return switch (sufi) {
            case "png", "PNG" -> MediaType.IMAGE_PNG_VALUE;
            case "jpg", "jpeg", "JPG", "JPEG" -> MediaType.IMAGE_JPEG_VALUE;
            case "gif", "GIF" -> MediaType.IMAGE_GIF_VALUE;
            case "mp4", "MP4" -> "video/mp4";
            default -> MediaType.APPLICATION_JSON_VALUE;
        };
    }

}
